/***************************************************************************
 *   This is a part of the NextCAD Web APP.                                *
 *   Copyright (C) AMCAX, All rights reserved.                             *
 ***************************************************************************/

import { pickedFaceData, pickedLineData } from '@amcax/base';
import {
  NumberInputFormat,
  PickInputRJSFFormat,
} from '@app-cad/common/components/command-form/constants';
import { PickableCommandForm } from '@app-cad/common/components/command-form/pickable';
import { useCommand } from '@app-cad/common/hooks/useCommand';
import { useTools } from '@app-cad/common/hooks/useTools';
import { CurvedBaseCommand, CurvedCmdDialogParams } from '@app-cad/types';
import { RJSFSchema } from '@rjsf/utils';
import { useAsyncEffect } from 'ahooks';
import i18n from 'i18next';
import { omitBy } from 'lodash';
import { useEffect, useMemo, useState } from 'react';

enum Continuity {
  Position = 0,
  Tangent = 1,
  Curvature = 3,
}

type FormData = {
  surface1?: pickedFaceData;
  edge1?: pickedLineData;
  continuity1: Continuity;
  parameter1: number;
  surface2?: pickedFaceData;
  edge2?: pickedLineData;
  continuity2: Continuity;
  parameter2: number;
  isPrecise: boolean;
  tol0?: number;
  tol1?: number;
  tol2?: number;
  autoReverse: boolean;
};

type ParamsSurface = {
  id: string;
  edge: string;
  continuity: Continuity;
  parameter: number;
};

type Params = {
  surface1: ParamsSurface;
  surface2: ParamsSurface;
  isPrecise: boolean;
  tol0: number;
  tol1: number;
  tol2: number;
  autoReverse: boolean;
};

function CommandBlendSurface({ title, onClose, props }: CurvedCmdDialogParams) {
  const initData = {
    continuity1: Continuity.Position,
    parameter1: 0.5,
    continuity2: Continuity.Position,
    parameter2: 0.5,
    isPrecise: false,
    autoReverse: true,
  } as FormData;

  const [formData, setFormData] = useState<FormData>(initData);

  const { picker } = useTools();

  const execute = async (preview: boolean) => {
    const {
      surface1,
      edge1,
      continuity1,
      parameter1,
      surface2,
      edge2,
      continuity2,
      parameter2,
      isPrecise,
      tol0,
      tol1,
      tol2,
      autoReverse,
    } = formData;

    const params: Params = {
      surface1: {
        id: surface1.meshId,
        edge: edge1.edgeId,
        continuity: continuity1,
        parameter: parameter1,
      },
      surface2: {
        id: surface2.meshId,
        edge: edge2.edgeId,
        continuity: continuity2,
        parameter: parameter2,
      },
      isPrecise,
      tol0: isPrecise ? tol0 : null,
      tol1: isPrecise ? tol1 : null,
      tol2: isPrecise ? tol2 : null,
      autoReverse,
    };

    await confirmCommand({ type: 'Blend', a: params }, preview);
  };

  useEffect(() => {
    preview();
  }, [formData]);

  useAsyncEffect(async () => {
    if (props == null) {
      setFormData(initData);
      return;
    }

    const params: Params = props.params;

    const { surface1, surface2, isPrecise, tol0, tol1, tol2, autoReverse } =
      params;

    await initEditDependency([
      surface1.id,
      surface1.edge,
      surface2.id,
      surface2.edge,
    ]);

    setFormData({
      surface1: picker.generatePickObjByPickID(surface1.id) as pickedFaceData,
      edge1: picker.generatePickObjByPickID(surface1.edge) as pickedLineData,
      continuity1: surface1.continuity,
      parameter1: surface1.parameter,
      surface2: picker.generatePickObjByPickID(surface2.id) as pickedFaceData,
      edge2: picker.generatePickObjByPickID(surface2.edge) as pickedLineData,
      continuity2: surface2.continuity,
      parameter2: surface2.parameter,
      isPrecise,
      tol0: isPrecise ? tol0 : null,
      tol1: isPrecise ? tol1 : null,
      tol2: isPrecise ? tol2 : null,
      autoReverse,
    });
  }, []);

  const checkAndFinishDraw = async () => {
    if (!isFormDataValid()) {
      return;
    }

    execute(false);

    onClose();
  };

  const { initEditDependency, initingEdit, confirmCommand, clear, isLoading } =
    useCommand('cmd-blend-surface', {
      commandName: 'CreateSurface',
      editDxid: props?.shape,
      onClose,
      finishDraw: checkAndFinishDraw,
    });

  const isFormDataValid = () => {
    const {
      surface1,
      edge1,
      parameter1,
      surface2,
      edge2,
      parameter2,
      isPrecise,
      tol0,
      tol1,
      tol2,
    } = formData;

    const isPreciseValid =
      !isPrecise || (tol0 != null && tol1 != null && tol2 != null);

    return (
      surface1 != null &&
      edge1 != null &&
      parameter1 != null &&
      surface2 != null &&
      edge2 != null &&
      parameter2 != null &&
      isPreciseValid
    );
  };

  const preview = async () => {
    if (!isFormDataValid()) {
      clear();
      return;
    }

    await execute(true);
  };

  const continuitySchema = {
    type: 'number',
    oneOf: [
      {
        type: 'number',
        title: '位置',
        const: 0,
      },
      {
        type: 'number',
        title: '切线',
        const: 1,
      },
      {
        type: 'number',
        title: '曲率',
        const: 3,
      },
    ],
    default: 0,
  } as RJSFSchema;

  const schema: RJSFSchema = useMemo(() => {
    return omitBy(
      {
        type: 'object',
        properties: {
          surface1: {
            type: 'string',
            format: PickInputRJSFFormat.PickSurface,
          },
          edge1: {
            type: 'string',
            format: PickInputRJSFFormat.PickCurve,
          },
          continuity1: {
            title: '曲面1连续方式',
            ...continuitySchema,
          },
          parameter1: {
            type: 'number',
            title: '曲面1参数',
            format: NumberInputFormat.Real,
          },
          surface2: {
            type: 'string',
            format: PickInputRJSFFormat.PickSurface,
          },
          edge2: {
            type: 'string',
            format: PickInputRJSFFormat.PickCurve,
          },
          continuity2: {
            title: '曲面2连续方式',
            ...continuitySchema,
          },
          parameter2: {
            type: 'number',
            title: '曲面2参数',
            format: NumberInputFormat.Real,
          },
          isPrecise: {
            type: 'boolean',
            title: '容差限制',
          },
          tol0: formData.isPrecise && {
            type: 'number',
            title: '位置容差',
            format: NumberInputFormat.Real,
          },
          tol1: formData.isPrecise && {
            type: 'number',
            title: '位置公差',
            format: NumberInputFormat.Real,
          },
          tol2: formData.isPrecise && {
            type: 'number',
            title: '曲率相对误差公差',
            format: NumberInputFormat.Real,
          },
          autoReverse: {
            type: 'boolean',
            title: '自动翻转面的方向',
          },
        },
      },
      (v) => !v,
    );
  }, [formData.isPrecise]);

  return (
    <PickableCommandForm
      disabled={initingEdit}
      onClose={onClose}
      title={title}
      schema={schema}
      formData={formData}
      onChange={(v) => {
        setFormData(v);
      }}
      submitLoading={isLoading}
      extraUiSchema={{
        surface1: {
          'ui:placeholder': '请输入曲面1',
          'ui:autofocus': true,
        },
        edge1: {
          'ui:placeholder': '请输入曲面1的边界',
        },
        surface2: {
          'ui:placeholder': '请输入曲面2',
        },
        edge2: {
          'ui:placeholder': '请输入曲面2的边界',
        },
      }}
      submitText='完成'
      onSubmit={checkAndFinishDraw}
      isFormDataValid={isFormDataValid()}
    />
  );
}

export const cmdBlendSurface: CurvedBaseCommand = {
  id: 'CmdBlendSurface',
  label: 'command.blend-surface',
  icon: 'commands/curved/blend-surface',
  create: (label, onClose, props) => (
    <CommandBlendSurface
      title={i18n.t(label)}
      onClose={onClose}
      props={props}
    />
  ),
};
